package com.hitqz.robot.dispatch.netty.decoder;

import com.hitqz.robot.api.dispatch.model.MessageDto;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 机器人控制信息的解码器
 * @author xupkun
 * @date 2023/8/4
 */
@Slf4j
public class Server2RobotDecoder extends ByteToMessageDecoder {


	@Override
	protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
		try {
			byteBuf.markReaderIndex();
			short version = byteBuf.readShort();

			byte[] clientIdData = new byte[32];

			byteBuf.readBytes(clientIdData);
			String clientId = new String(clientIdData).trim();
			int sn = byteBuf.readInt();
			short cmd = byteBuf.readShort();
			int dataLength = byteBuf.readInt();
			byte[] data = new byte[dataLength];
			if (dataLength < byteBuf.readableBytes()) {
				byteBuf.resetReaderIndex();
				return ;
			}
			byteBuf.readBytes(data);
			MessageDto msg = new MessageDto();
			msg.setClientId(clientId);
			msg.setCmd(cmd);
			msg.setDataLength(dataLength);
			msg.setData(data);
			msg.setHeader(new byte[]{
					(byte) 0xEB, (byte) 0x90
			});
			msg.setSn(sn);
			list.add(msg);
		}catch (Exception e) {
			//byteBuf.readBytes(byteBuf.readableBytes());
			log.info("Failed to read" + e.getMessage());
		}
	}
}
